package com.common.service.impl;

import com.common.constant.SystemConstants;
import com.common.domain.entity.LoginUser;
import com.common.domain.entity.ResponseResult;
import com.common.domain.entity.User;
import com.common.domain.vo.LoginUserVo;
import com.common.domain.vo.UserInfoVo;
import com.common.enums.AppHttpCodeEnum;
import com.common.service.LoginServer;
import com.common.util.BeanCopyUtils;
import com.common.util.JwtUtil;
import com.common.util.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * @author 
 **/
@Service
public class LoginServerImpl implements LoginServer {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());


        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判断认证是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //判断状态是否停用
        //获取用户的userid,生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if(!loginUser.getUser().getStatus().equals(SystemConstants.STATUS_NORMAL)){
           return  ResponseResult.errorResult(AppHttpCodeEnum.STATUS_EX);
        }
        String jwt = null;
        try {
            //将对象转换成流存储在jwt中
            jwt = JwtUtil.createJWT(SerializeUtils.serialize(loginUser));
        } catch (IOException e) {
            e.printStackTrace();
        }


        //把token和userInfo封装返回
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        userInfoVo.setCardId(userInfoVo.getCardId().substring(0,5)+"*****"+userInfoVo.getCardId().substring(13));
        userInfoVo.setPhoneNumber(userInfoVo.getPhoneNumber().substring(0,3)+"****"+userInfoVo.getPhoneNumber().substring(7));
        LoginUserVo loginUserVo = new LoginUserVo(jwt , userInfoVo);

        return  ResponseResult.okResult(loginUserVo);
    }

    @Override
    public ResponseResult logout() {
        //得到用户的登录信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //得到id信息
        Long userId = loginUser.getUser().getId();

        return ResponseResult.okResult();
    }
}
